class WXChat {
    // 客户端ip地址
    ipAddress: string = '0.0.0.0';
    refreshtoken: string = "";
    headimgurl: string = null;
    _wechatTokens: {
        accessToken: "",
        refreshtoken: "",
        openid: "",
    };
    isWxLogin: boolean = false;
    wxappid: "wx817ab948bdf11ea5";
    wxappsecret: "842d3ccddad18b2c8d2fb5d12268ce2c ";
    //用途
    wxState = {
        //登录
        USE_TO_LOGIN: 'wechat_sdk_login',
        //绑定微信
        USE_TO_BINDING: 'wechat_sdk_binding',
        USE_TO_SHARE: "use_to_share",
    }

    //分享类型
    wxShareType = {
        TEXT: 0,
        IMG: 1,
        MUSIC: 2,
        VIDEO: 3,
        WEB_PAGE: 4
    }

    wxScene = {
        //分享到对话
        WXSceneSession: 0,
        //分享到朋友圈
        WXSceneTimeline: 1,
        //分享到收藏
        WXSceneFavorite: 2
    }
    init() {
        this.wxappid = cc.vv.GLConfig.wxappid;
        this.wxappsecret = cc.vv.GLConfig.wxsecrete;
    }

    /**
     * @description 微信分享
     * @param {*} reqContent 
     */
    wxShare(reqContent) {
        if (cc.sys.isNative) {
            cc.vv.GLSDKMgr.wxShare(reqContent)
        }
    }
    /**
     * @description 微信分享回调
     * @param {*} code 
     */
    onShared(msg) {
        cc.vv.GLUtils.showTips(msg);
    }
    /**
     * @description 注册到微信
     */
    regToWx() {
        if (cc.sys.isNative && this.wxappid) {
            cc.vv.GLSDKMgr.registerWeChat(this.wxappid)
        }
    }

    getWxAuth(reqState) {
        //原生app调用
        if (cc.sys.isNative) {
            cc.vv.GLSDKMgr.sendWxAuthRequest(reqState)
        }
    }

    /**
     * @description 用户同意授权后的回调
     * @param {临时授权码} code 
     * @param {用途} state 
     */
    onGetWxAuth(code, state) {
        switch (state) {
            case this.wxState.USE_TO_LOGIN:
                this.getTokenAndOpenid(code);
                break;
            case this.wxState.USE_TO_SHARE:
                //this.onShared(code);
                break;
            default:
                break;
        }
    }
    /**
     * @description 用户取消或者拒绝授权
     * @param {临时授权码} code 
     * @param {用途} state 
     */
    onCancelWxAuth() {
    }
    /**
     * @description 拉起微信授权界面
     * @param {用途} reqState 
     */
    getWxAuthToLogin() {
        var install = cc.vv.GLSDKMgr.checkInstallWX()
        if (!install) {
            cc.vv.GLUtils.showTips("手机未安装微信");
            cc.vv.GLSDKMgr.loginFailedCallback();
            return;
        }
        let wechatTokenStr = cc.sys.localStorage.getItem("wechatToken");
        if (!wechatTokenStr) {
            console.log("没有token时进入");
            this.getWxAuth(this.wxState.USE_TO_LOGIN);
        } else {
            let wechatToken = JSON.parse(wechatTokenStr);
            let accessToken = wechatToken.accessToken;
            let refreshtoken = wechatToken.refreshtoken;
            let openid = wechatToken.openid;
            console.log("wechatToken =  :",wechatToken);
            console.log("有token时进入 accessToken =" + accessToken + " refreshtoken=" + refreshtoken+"wechatToken = ",wechatToken);

            this._wechatTokens = {
                accessToken: accessToken,
                refreshtoken: refreshtoken,
                openid: openid,
            }

            let url = "https://api.weixin.qq.com/sns/auth";
            let params = {
                access_token: accessToken,
                openid: openid
            }
            cc.vv.GLHttpUtils.httpGet(url, params, this.checkAccessTokenIsAvalable.bind(this));
        }
    }

    checkAccessTokenIsAvalable(resDataString) {
        let resData = JSON.parse(resDataString);
        let errcode = parseInt(resData.errcode);
        console.log("检查token是否可用 :",resData);
        console.log("this._wechatTokens = ",this._wechatTokens);
        if (errcode == 0) {
            //请求个人信息以登录
            let url = "https://api.weixin.qq.com/sns/userinfo";
            let params = {
                access_token: this._wechatTokens.accessToken,
                openid: this._wechatTokens.openid
            }
            cc.vv.GLHttpUtils.httpGet(url, params, this.onUserData.bind(this));
        } else {
            //刷新access_token
            let url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
            let params = {
                appid: this.wxappid,
                grant_type: "refresh_token",
                refresh_token: this._wechatTokens.refreshtoken,
            }
            cc.vv.GLHttpUtils.httpGet(url, params, this.onRefreshToken.bind(this));
        }
    }
    getTokenAndOpenid(code) {
        let url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        let params = {
            appid: this.wxappid,
            secret: this.wxappsecret,
            code: code,
            grant_type: "authorization_code"
        }
        cc.vv.GLHttpUtils.httpGet(url, params, this.onRefreshToken.bind(this));
    }

    onRefreshToken(resDataString) {
        console.log("onRefreshToken = " + resDataString);
        let resData = JSON.parse(resDataString);
        if (resData.errcode) {
            switch (parseInt(resData.errcode)) {
                case 40029: {
                    cc.log("请求token 错误");
                }
                    break;
                case 40030: {
                    cc.log("刷新token 错误");
                }
                    break;
            }
            cc.log("获取token 错误 清除token 下次点击拉起微信 重新认证");
            cc.vv.GLUtils.showTips("获取微信token错误,请重试!");
            cc.sys.localStorage.removeItem("wechatToken");
            cc.vv.GLSDKMgr.loginFailedCallback();
            return;
        }
        // let expires_in = resData.expires_in;
        // let unionid = resData.unionid;
        let accessToken = resData.access_token;
        this.refreshtoken = resData.refresh_token;
        let openid = resData.openid;

        // console.log("refreshtoken = "+ this.refreshtoken);
        let wechatToken = {
            accessToken: resData.access_token,
            refreshtoken: resData.refresh_token,
            openid: resData.openid,
        }
        cc.sys.localStorage.setItem("wechatToken", JSON.stringify(wechatToken));

        let url = "https://api.weixin.qq.com/sns/userinfo";
        let params = {
            access_token: accessToken,
            openid: openid
        }
        cc.vv.GLHttpUtils.httpGet(url, params, this.onUserData.bind(this));
    }

    onUserData(resDataString) {
        console.log("onUserData = " + resDataString);
        //拿到信息后准备登录
        let resData = JSON.parse(resDataString);

        // let userinfo = {
        //     avatar: resData.headimgurl,
        //     sex: resData.sex,
        //     rolename: resData.nickname,
        //     unionId: resData.unionid,
        //     refreshToken: this.refreshtoken,
        //     password: this.refreshtoken,
        //     openId: resData.openid,
        // }

        let userinfo = {
            auth_type:"WECHAT",
            phone:"",
            vcode:"",
            //wechat_token:this.refreshtoken ||  this._wechatTokens.refreshtoken,
            wechat:resData.unionid,   //o3tyX0fk3YjXln9IoLHdaNTRJwDk
            ip:"127.0.0.1",
            location:resData.city || "未知",
            device_type: cc.vv.GLUtils.getPhoneType(),
            device_imei: cc.vv.GLSDKMgr.getDeviceBrand(),
            wechat_logo:resData.headimgurl,
            wechat_name:resData.nickname,
            wechat_sex:resData.sex,
        }
        console.log("调试userinfo = ",userinfo);
        cc.vv.GLSDKMgr.wechatLoginCallback(userinfo)
        console.log("onUserData headimgurl = " + this.headimgurl);
    }
}
export let wxChat: WXChat = new WXChat();

